package sz.szsmk.citizencard.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.chenenyu.router.annotation.Route;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.model.network.bean.AuthResult;
import sz.szsmk.citizencard.databinding.BindActivityBinding;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.dialog.TwoButtonDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.BindThirdRes;
import sz.szsmk.citizencard.model.network.bean.response.OauthTokenRes;
import sz.szsmk.citizencard.mvp.contract.IBindContact;
import sz.szsmk.citizencard.mvp.presenter.BindListPresenter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.PubUtils;

//import com.tencent.tauth.IUiListener;
//import com.tencent.tauth.Tencent;
//import com.tencent.tauth.UiError;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/7/10 15:15
 * description:
 */
@Route("bind")
public class BindActivity extends IBaseActivity<BindListPresenter, BindActivityBinding>
        implements IBindContact.IBindView, View.OnClickListener {
    private List<BindThirdRes.ThirdAppUserExBean> thirdAppUserEx = new ArrayList<>();

    private static final int SDK_AUTH_FLAG = 2;
    private int loginType;
    public String uid;
    private String accessToken;
    private String typeTv = "";

    @Override
    protected int attachLayoutRes() {
        return R.layout.bind_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        accessToken = ACache.get(this).getAsString("access_token");
        TextView title = (TextView) findViewById(R.id.setting_title);
        ImageView back = (ImageView) findViewById(R.id.back);
        title.setOnClickListener(this);
        dataBinding.gobindWx.setOnClickListener(this);
        dataBinding.gobindQq.setOnClickListener(this);
        dataBinding.gobindAli.setOnClickListener(this);
        dataBinding.gobindWb.setOnClickListener(this);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title.setText("第三方账号绑定");
        mPresenter.getBindList();
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void getBindListFail() {
        PubUtils.popTipOrWarn(this, "网络错误");
    }

    @Override
    public void getBindListSucc(List<BindThirdRes.ThirdAppUserExBean> thirdAppUserEx) {
        this.thirdAppUserEx = thirdAppUserEx;
        for (int i = 0; i < thirdAppUserEx.size(); i++) {
            int loginType = thirdAppUserEx.get(i).getLoginType();
            if (loginType == 0) {
                dataBinding.gobindWx.setText("解绑");
                dataBinding.gobindWx.setTextColor(getResources().getColor(R.color.color_00AAFF));
            }
            if (loginType == 3) {
                dataBinding.gobindAli.setText("解绑");
                dataBinding.gobindAli.setTextColor(getResources().getColor(R.color.color_00AAFF));
            }
            if (loginType == 1) {
                dataBinding.gobindQq.setText("解绑");
                dataBinding.gobindQq.setTextColor(getResources().getColor(R.color.color_00AAFF));
            }
            if (loginType == 2) {
                dataBinding.gobindWb.setText("解绑");
                dataBinding.gobindWb.setTextColor(getResources().getColor(R.color.color_00AAFF));
            }
        }
    }

    @Override
    public void unBindSucc(BaseBean response) {

        final SuccessDialog dialog = new SuccessDialog(this, response.getMessage());
        dialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
            }
        }.start();

        if (loginType == 0) {
            dataBinding.gobindWx.setText("去绑定");
            dataBinding.gobindWx.setTextColor(getResources().getColor(R.color.color_3d494f));
        }
        if (loginType == 1) {
            dataBinding.gobindQq.setText("去绑定");
            dataBinding.gobindQq.setTextColor(getResources().getColor(R.color.color_3d494f));
        }
        if (loginType == 2) {
            dataBinding.gobindWb.setText("去绑定");
            dataBinding.gobindWb.setTextColor(getResources().getColor(R.color.color_3d494f));
        }
        if (loginType == 3) {
            dataBinding.gobindAli.setText("去绑定");
            dataBinding.gobindAli.setTextColor(getResources().getColor(R.color.color_3d494f));
        }

    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    String alipayOpenId = authResult.getAlipayOpenId();
                    String authCode = authResult.getAuthCode();
                    L.e(Constant.TAG, "支付宝----------------：" + alipayOpenId);
                    L.e(Constant.TAG, "支付宝----------：" + authCode);

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        uid = alipayOpenId;
                        mPresenter.bindThird(loginType + "", uid, accessToken);
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(BindActivity.this,
                                "授权失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.gobind_wx) {
            loginType = 0;
            typeTv = "微信";
            String wx = dataBinding.gobindWx.getText().toString().trim();
            if (wx.equals("去绑定")) {
                authorization(SHARE_MEDIA.WEIXIN);
            } else if (wx.equals("解绑")) {
                showNoticeDialog(typeTv, loginType);
            }
        } else if (id == R.id.gobind_qq) {
            loginType = 1;
            typeTv = "QQ";
            String qq = dataBinding.gobindQq.getText().toString().trim();
            if (qq.equals("去绑定")) {
                authorization(SHARE_MEDIA.QQ);
            } else if (qq.equals("解绑")) {
                showNoticeDialog(typeTv, loginType);
            }
        } else if (id == R.id.gobind_wb) {
            loginType = 2;
            typeTv = "新浪微博";
            String wb = dataBinding.gobindWb.getText().toString().trim();
            if (wb.equals("去绑定")) {
                authorization(SHARE_MEDIA.SINA);
            } else if (wb.equals("解绑")) {
                showNoticeDialog(typeTv, loginType);
            }
        } else if (id == R.id.gobind_ali) {
            loginType = 3;

            typeTv = "支付宝";
            String ali = dataBinding.gobindAli.getText().toString().trim();
            if (ali.equals("去绑定")) {
                mPresenter.oauthToken();
            }
            if (ali.equals("解绑")) {
                showNoticeDialog(typeTv, loginType);
            }
        }
    }

    private void showNoticeDialog(String typeTv, final int loginType) {
        final TwoButtonDialog dialog = new TwoButtonDialog(this, "解绑" + typeTv + "账户后你将无法继续使用它登录该智慧苏州账号");
        dialog.setCancelText("确认解绑");
        dialog.setOkTv("考虑一下");
        dialog.setTitleTv("解绑" + typeTv + "账户");
        dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {
                dialog.cancel();
            }
        });
        dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                mPresenter.unBind(loginType);
                dialog.cancel();
            }
        });
        dialog.show();
    }

    @Override
    public void oauthTokenSucc(OauthTokenRes response) {
        if (response != null) {
            String authInfo = response.getSign();
            alipayLogin(authInfo);
        }
    }

    private void alipayLogin(final String authInfo) {
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(BindActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(authInfo, true);
//                Map<String, String> result = authTask.authV2(testInfo, true);

                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @Override
    public void oauthTokenFail() {
        PubUtils.popTipOrWarn(this, "绑定失败");
    }

    @Override
    public void bindThirdSucc() {
        mPresenter.getBindList();
        //      删除授权
        SHARE_MEDIA media = null;
        if (loginType == 0)
            media = SHARE_MEDIA.WEIXIN;
        else if (loginType == 1)
            media = SHARE_MEDIA.QQ;
        else if (loginType == 2)
            media = SHARE_MEDIA.SINA;

        if (media == null)
            return;
        UMShareAPI.get(BindActivity.this).deleteOauth(BindActivity.this
                , media, null);
    }

    @Override
    public void bindThirdFail() {
        PubUtils.popTipOrWarn(this, "绑定失败");
    }

    @Override
    public void unBindFail(BaseBean response) {
        Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    public void authorization(SHARE_MEDIA share_media) {
        UMShareAPI.get(this).getPlatformInfo(this, share_media, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                L.e(Constant.TAG, "onStart " + "授权开始");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                L.e(Constant.TAG, "onComplete " + "授权完成");

                //sdk是6.4.4的,但是获取值的时候用的是6.2以前的(access_token)才能获取到值,未知原因
                String uid = map.get("uid");
                String openid = map.get("openid");//微博没有
                String unionid = map.get("unionid");//微博没有
                String access_token = map.get("access_token");
                String refresh_token = map.get("refresh_token");
                String expires_in = map.get("expires_in");
                String name = map.get("name");
                String gender = map.get("gender");
                String iconurl = map.get("iconurl");
                mPresenter.bindThird(loginType + "", uid, accessToken);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                L.e(Constant.TAG, "onError " + "授权失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                L.e(Constant.TAG, "onCancel " + "授权取消");
            }
        });
    }

}
